﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using System.Drawing;

namespace Anthony.Library
{
    public class FileSystemLibrary
    {
        /// <summary>
        /// Saves bytes to the given folder path and file name.
        /// Creates the folder if it does not already exist.
        /// </summary>
        /// <param name="folderPath"></param>
        /// <param name="fileName"></param>
        /// <param name="bytes"></param>
        public static void SaveFile(string folderPath, string fileName, byte [] bytes )
        {
            // Make sure the save folder exists
            if (!Directory.Exists(folderPath))
                Directory.CreateDirectory(folderPath);

            FileStream fileStream = new FileStream(folderPath + fileName, FileMode.Create, FileAccess.Write);
            MemoryStream memoryStream = new MemoryStream(bytes);
            ReadWriteStream(memoryStream, fileStream);
        }


        /// <summary>
        /// Reads from readStream, writes to writeSteam.
        /// </summary>
        /// <param name="readStream"></param>
        /// <param name="writeStream"></param>
        protected static void ReadWriteStream(Stream readStream, Stream writeStream)
        {
            int length = 256;
            Byte[] buffer = new Byte[length];
            int bytesRead = readStream.Read(buffer, 0, length);
            // write the required bytes
            while (bytesRead > 0)
            {
                writeStream.Write(buffer, 0, bytesRead);
                bytesRead = readStream.Read(buffer, 0, length);
            }
            readStream.Close();
            writeStream.Close();
        }


        public static void SaveImage(string folderPath, string fileName, byte[] bytes)
        {
            Bitmap b = new Bitmap(new MemoryStream(bytes));
            b.Save(folderPath + fileName);
            b.Dispose();
        }


        public static void SaveThumbnailImage(string folderPath, string fileName, byte[] bytes, int width, int height)
        {
            Bitmap b = new Bitmap(new MemoryStream(bytes));
            Image thumbnail = b.GetThumbnailImage(width, height, null, IntPtr.Zero);
            thumbnail.Save(folderPath + fileName);
            b.Dispose();
            thumbnail.Dispose();
        }
    }
}
